//
//  SWEventDetailViewController.swift
//  ChildStory
//
//  Created by linhan on 2016/11/14.
//  Copyright © 2016年 Aiya. All rights reserved.
//

import Foundation
import UIKit
class SWEventDetailViewController: SWBaseViewController,SWAPIComponent,ScrollADImageDelagate,ClickActionDelegate,UICollectionViewDataSource,UICollectionViewDelegate,UIScrollViewDelegate,CollectionViewCellDelegate,SWImagePickerControllerDelegate,SWEventPhotosViewDelegate,SWGlobalPopupMenu,SWALPhotosCollectionViewControllerDelegate
{
    var eventID:String = ""
    var showPhoto:Bool = false
    var popupMenuController:AnyObject?
    
    private var _event:SWKidEvent?
    
    private var _musics:[SWMusic] = []
    
    //整体左边距
    private let LeftMargin:CGFloat = 8
    //整体右边距
    private let RightMargin:CGFloat = 8
    //区块与区块的间距
    private let Grid:CGFloat = 8
    
    private let MainScrollViewTag:Int = 1
    private let VCollectionViewTag:Int = 2
    private var NavigationBarHoverY:CGFloat = 0
    
    private var _photos:[SWALPhoto] = []
    private var _favoritePhotos:[SWALPhoto] = []
    private var _addItem:SWALPhoto = SWALPhoto(thumbnail: UIImage(named:"event_detail_btn_add"))
    
    private var _container:UIScrollView = UIScrollView()
    private var _navigationBar:UIView = UIView()
    
    private var _featuresView:UIView = UIView()
    private var _coverView:SWGroupView?
    lazy private var _gameView:UIImageView = UIImageView()
    lazy private var _photoView:SWEventPhotosView = SWEventPhotosView()
    lazy private var _titleLabel:UILabel = UILabel()
    lazy private var _titleViewLabel:UILabel = UILabel()
    lazy private var _expandBtn:UIButton = UIButton(type: .custom)
    lazy private var _collectBtn:UIButton = UIButton(type: .custom)
    
    override var prefersNavigationBarHidden: Bool{
        return true
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setup()
    }
    
    deinit
    {
        trace("DEINIT SWEventDetailViewController")
    }
    
    private func setup()
    {
        automaticallyAdjustsScrollViewInsets = false
        view.backgroundColor = UIColor(hex: 0xf5f5f5)
        
        _container.frame = view.bounds
        _container.alwaysBounceVertical = true
        _container.scrollsToTop = true
        _container.alpha = 0
        _container.tag = MainScrollViewTag
        _container.delegate = self
        view.addSubview(_container)
        
        createNavigationBar()
        globalPopupMenuSetup(container: view)
        
        let backBtn:UIButton = UIButton(type: .custom)
        backBtn.setImage(UIImage(named:"global_btn_back"), for: .normal)
        backBtn.sizeToTouchEasy()
        backBtn.center = CGPointMake(15, 44)
        backBtn.addTarget(self, action: #selector(backBtnTapped), for: .touchUpInside)
        view.addSubview(backBtn)
        
        //==============banner
        let coverTopMargin:CGFloat = 20
        let coverBottomMargin:CGFloat = 43
        let coverHeight:CGFloat = SWGroupView.getHeight(containerWidth: view.width)
        let bannerHeight:CGFloat = coverTopMargin + coverHeight + coverBottomMargin
        NavigationBarHoverY = coverTopMargin + coverHeight
        
        let bannerContainer:UIView = UIView()
        bannerContainer.frame = CGRectMake(0, 0, view.width, bannerHeight)
        bannerContainer.backgroundColor = UIColor.white
        _container.addSubview(bannerContainer)
        
        let coverView = SWGroupView(frame: CGRectMake(0, coverTopMargin, view.width, coverHeight))
        coverView.delegate = self
        bannerContainer.addSubview(coverView)
        _coverView = coverView
        
        let titleRightMargin:CGFloat = 100
        _titleLabel.textColor = UIColor(hex: 0x302f2f)
        _titleLabel.font = UIFont.systemFont(ofSize: 17)
        _titleLabel.frame = CGRectMake(LeftMargin, coverView.bottom + 9, view.width - LeftMargin - titleRightMargin, 21)
        bannerContainer.addSubview(_titleLabel)
        
        //内容
        _featuresView.frame = CGRectMake(0, bannerContainer.bottom + Grid, view.width, 0)
        _featuresView.backgroundColor = UIColor.white
        _container.addSubview(_featuresView)
        
        let gameViewHeight:CGFloat = view.width * 0.5324
        _gameView.frame = CGRectMake(0, 0, view.width, gameViewHeight)
        _gameView.clipsToBounds = true
        _gameView.contentMode = .scaleAspectFill
        _gameView.image = UIImage(named:"event_image_game")
        _container.addSubview(_gameView)
        
        //照片集合
        _expandBtn.setImage(UIImage(named:"event_detail_btn_expand"), for: .normal)
        _expandBtn.sizeToTouchEasy()
        _expandBtn.center = CGPointMake(view.width - 53, bannerContainer.height - 15)
        _expandBtn.addTarget(self, action: #selector(expandBtnTapped), for: .touchUpInside)
        bannerContainer.addSubview(_expandBtn)
        
        _photoView.setup(containerWidth: view.width)
        _photoView.y = bannerContainer.bottom + Grid
        _photoView.alpha = 0
        _photoView.hCollectionView?.delegate = self
        _photoView.hCollectionView?.dataSource = self
        _photoView.vCollectionView?.delegate = self
        _photoView.vCollectionView?.dataSource = self
        _photoView.vCollectionView?.tag = VCollectionViewTag
        _photoView.delegate = self
        _container.addSubview(_photoView)
        
        SWNotificationCenter.addObserver(self, selector: #selector(deleteAssetNotification(_:)), name: NotificationName.DeleteAsset, object: nil)
        SWNotificationCenter.addObserver(self, selector: #selector(assetChangedNotification(_:)), name: NotificationName.AssetChanged, object: nil)
        
        reloadData()
        
        DispatchQueue.global(priority: .default).async {
            self.loadPhoto()
        }
        
        if showPhoto
        {
            photoViewExpand()
        }
    }
    
    private func updateScrollBanner()
    {
        let images:[Any] = _event?.exampleImages?.flatMap({$0 as? String}) ?? []
        _coverView?.data = images
    }
    
    private func updateView()
    {
        guard let event = _event else {
            return
        }
        
        _titleLabel.text = event.title
        _titleViewLabel.text = event.title
        
        updateScrollBanner()
        
        let contentWidth:CGFloat = view.width - LeftMargin - RightMargin
        var lastBottom:CGFloat = 0
        _featuresView.removeAllSubview()
        let features:[SWKidEventFeature] = event.features?.flatMap({$0 as? SWKidEventFeature}) ?? []
        for (i,feature) in features.enumerated()
        {
            let TopMargin:CGFloat = 15
            let BottomMargin:CGFloat = 14
            let y:CGFloat = lastBottom + TopMargin
            
            if i > 0
            {
                //分割线
                let line:UIView = UIView()
                line.backgroundColor = UIColor(white: 0.97, alpha: 1)
                line.frame = CGRectMake(LeftMargin, lastBottom, contentWidth, 1)
                _featuresView.addSubview(line)
            }
            
            let titleLabel:UILabel = UILabel()
            titleLabel.font = UIFont.systemFont(ofSize: 15)
            titleLabel.textColor = UIColor(hex: 0x313030)
            titleLabel.text = feature.title
            titleLabel.frame = CGRectMake(LeftMargin, y, contentWidth, 19)
            _featuresView.addSubview(titleLabel)
            
            let font = UIFont.systemFont(ofSize: 14)
            let content:String = feature.content ?? ""
            let textHeight:CGFloat = StringUtil.getStringHeight(content, font: font, width: contentWidth)
            let contentLabel = UILabel()
            contentLabel.numberOfLines = 0
            contentLabel.font = font
            contentLabel.text = content
            contentLabel.textColor = UIColor(hex: 0x313030)
            contentLabel.frame = CGRectMake(LeftMargin, titleLabel.bottom + 15, contentWidth, textHeight)
            _featuresView.addSubview(contentLabel)
            
            lastBottom = contentLabel.bottom + BottomMargin
        }
        _featuresView.height = lastBottom
        
        
        _gameView.y = _featuresView.bottom + Grid
        
        _container.contentSize = CGSizeMake(_container.width, _gameView.bottom)
        UIView.animate(withDuration: 0.3, animations: {
            self._container.alpha = 1
        })
    }
    
    private func createNavigationBar()
    {
        _navigationBar.frame = CGRectMake(0, 0, view.width, 64)
        _navigationBar.backgroundColor = UIColor(hex: 0xf8e9eb)
        _navigationBar.alpha = 0
        view.addSubview(_navigationBar)
        
        let titleHeight:CGFloat = 22
        _titleViewLabel.font = UIFont.systemFont(ofSize: 18)
        _titleViewLabel.textColor = UIColor(hex: 0x333031)
        _titleViewLabel.frame = CGRectMake(40, 32, view.width - 80, titleHeight)
        _titleViewLabel.textAlignment = .center
        _navigationBar.addSubview(_titleViewLabel)
        
        _collectBtn.setImage(UIImage(named:"event_detail_nav_btn_dislike"), for: .normal)
        _collectBtn.setImage(UIImage(named:"event_detail_nav_btn_like"), for: .selected)
        _collectBtn.sizeToTouchEasy()
        _collectBtn.addTarget(self, action: #selector(collectBtnTapped), for: .touchUpInside)
        _collectBtn.center = CGPointMake(_navigationBar.width - 23, 44)
        _navigationBar.addSubview(_collectBtn)
    }
    
    private func reloadData()
    {
        let req = SWEventDetailFetchReq()
        req.eventID = eventID
        req.successCallback = {[weak self] response,cache in
            if let response = response as? SWEventDetailFetchRsp,
               let eventRsp = response.event,
               let event = SWKidEvent(response: eventRsp)
            {
                self?._event = event
                self?.updateView()
            }
        }
        req.failCallback = {[weak self] error in
        
        }
        load(req)
    }
    
    private func loadPhoto()
    {
        if eventID == ""
        {
            return
        }
        
        let assets = SWAssetsManager.sharedManager().assets.filter({($0.eventID ?? "") == eventID})
        var favorites:[SWAssetRecord] = assets.filter({$0.valid && $0.isFavorite})
        var normals:[SWAssetRecord] = assets.filter({$0.valid && !$0.isFavorite})
        //最新收藏的排在前面
        favorites.sort(by: {$0.favoriteTime > $1.favoriteTime})
        normals.sort(by: {$0.favoriteTime > $1.favoriteTime})
        if favorites.count > 0 || normals.count > 0
        {
            let favoriteIDs:[String] = favorites.map({$0.localID})
            let normalIDs:[String] = normals.map({$0.localID})
            _favoritePhotos = SWAssetsLibraryHelper.shared().fetchAssets(localIdentifiers: favoriteIDs)
            for photo in _favoritePhotos
            {
                photo.selected = true
            }
            _photos += SWAssetsLibraryHelper.shared().fetchAssets(localIdentifiers: normalIDs)
            
            DispatchQueue.main.async {
                self._photoView.hCollectionView?.reloadData()
                self._photoView.vCollectionView?.reloadData()
            }
        }
    }
    
    //展开照片
    private func photoViewExpand()
    {
        let containerHeight = self.view.height - max(_photoView.y - _container.contentOffset.y, 0)
        _photoView.expand(containerHeight: containerHeight)
    }
    
    //移除照片
    private func removePhoto(localID:String, photos:inout [SWALPhoto], collectionView:UICollectionView?)
    {
        if let index = photos.index(where: {$0.localIdentifier == localID})
        {
            photos.removeAtIndexSafely(index)
            collectionView?.reloadData()
        }
    }
    
    //更换照片
    private func replacePhoto(oldLocalID:String, newLocalID:String, photos:inout [SWALPhoto], collectionView:UICollectionView?)
    {
        if let index = photos.index(where: {$0.localIdentifier == oldLocalID})
        {
            //photos.removeAtIndexSafely(index)
            let selected:Bool = photos.valueAt(index)?.selected ?? false
            let library = SWAssetsLibraryHelper.shared()
            if let photo = library.fetchAssets(localIdentifiers: [newLocalID]).valueAt(0)
            {
                //photos.insertSafely(photo, atIndex: index)
                photos.replaceSubrange(index...index, with: [photo])
                photo.selected = selected
            }
            collectionView?.reloadData()
        }
    }
    
    private func likeKidEvent(_ eventID:String)
    {
        let req = SWLikeKidEventReq()
        req.eventID = eventID
        req.successCallback = {[weak self] _,_ in
            self?.updateCollecteStatus(collected:true)
        }
        req.failCallback = {[weak self] error in
            self?._collectBtn.isEnabled = true
            SVProgressHUD.showError(withStatus: error.message)
        }
    }
    
    private func dislikeKidEvent(_ eventID:String)
    {
        let req = SWLikeKidEventReq()
        req.eventID = eventID
        req.successCallback = {[weak self] _,_ in
            self?.updateCollecteStatus(collected:false)
        }
        req.failCallback = {[weak self] error in
            self?._collectBtn.isEnabled = true
            SVProgressHUD.showError(withStatus: error.message)
        }
    }
    
    private func updateCollecteStatus(collected:Bool)
    {
        _collectBtn.isEnabled = true
        _collectBtn.isSelected = collected
        _event?.isFavorite = collected
        let status:String = collected ? "成功收藏" : "取消收藏"
        let imageNamed:String = collected ? "event_detail_nav_btn_like" : "event_detail_nav_btn_dislike"
        SVProgressHUD.show(UIImage(named:imageNamed), status: status)
    }
    
    //MARK ============================================================================================
    //==============================            Delegate           ===============================
    //=================================================================================================
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int
    {
        return collectionView.tag == VCollectionViewTag ? (_photos.count + 1) : _favoritePhotos.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell
    {
        let index:Int = indexPath.row
        let photo:SWALPhoto? = collectionView.tag == VCollectionViewTag ? _photos.valueAt(index - 1) : _favoritePhotos.valueAt(index)
        var cell:UICollectionViewCell?
        if collectionView.tag == VCollectionViewTag && indexPath.row == 0
        {
            cell = collectionView.dequeueReusableCell(withReuseIdentifier: "SWEventPhotoAddCollectionCell", for: indexPath)
        }
        else
        {
            let photoCell:SWEventPhotoCollectionCell? = collectionView.dequeueReusableCell(withReuseIdentifier: "SWEventPhotoCollectionCell", for: indexPath) as? SWEventPhotoCollectionCell
            photoCell?.delegate = self
            photoCell?.photo = photo
            photo?.fetchThumbnail()
            cell = photoCell
        }
        return cell ?? UICollectionViewCell()
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath)
    {
        if collectionView.tag == VCollectionViewTag
        {
            if indexPath.row == 0
            {
                let pickerController = SWImagePickerController()
                pickerController.delegate = self
                pickerController.allowsMultipleSelection = true
                pickerController.maxCount = 0
                let navigation = SWBaseNavigationController(rootViewController: pickerController)
                present(navigation, animated: true, completion:nil)
            }
            else
            {
                let localIdentifiers:[String] = _photos.flatMap({$0.localIdentifier}).filter({$0 != ""})
                let viewController = SWPhotosDetailViewController(localIdentifiers: localIdentifiers)
                viewController.index = indexPath.row - 1
                navigationController?.pushViewController(viewController, animated: true)
            }
        }
        else
        {
            let localIdentifiers:[String] = _favoritePhotos.flatMap({$0.localIdentifier}).filter({$0 != ""})
            let viewController = SWPhotosDetailViewController(localIdentifiers: localIdentifiers)
            viewController.index = indexPath.row
            navigationController?.pushViewController(viewController, animated: true)
        }
    }
    
    func collectionViewCell(_ cell:UICollectionViewCell, click action:String, argument aArgument:[AnyHashable:Any]?)
    {
        if action == CallbackAction.Favorite
        {
            if let cell = cell as? SWEventPhotoCollectionCell,
               let photo = cell.photo,
               let localID = aArgument?["localID"] as? String,
               let isFavorite:Bool = aArgument?["favorite"] as? Bool
            {
                photo.selected = isFavorite
                if isFavorite
                {
                    if let index = _photos.index(where: {$0.localIdentifier == localID})
                    {
                        _photos.removeAtIndexSafely(index)
                        _photoView.vCollectionView?.deleteItems(at: [IndexPath(row: index + 1, section: 0)])
                    }
                    _favoritePhotos.insert(photo, at: 0)
                    _photoView.hCollectionView?.insertItems(at: [IndexPath(row: 0, section: 0)])
                }
                else
                {
                    if let index = _favoritePhotos.index(where: {$0.localIdentifier == localID})
                    {
                        _favoritePhotos.removeAtIndexSafely(index)
                        _photoView.hCollectionView?.deleteItems(at: [IndexPath(row: index, section: 0)])
                    }
                    _photos.insert(photo, at: 0)
                    _photoView.vCollectionView?.insertItems(at: [IndexPath(row: 1, section: 0)])
                }
                
                SWAssetsManager.sharedManager().changeAsset(localID: localID, favorite: isFavorite)
            }
        }
    }
    
    func argumentForGlobalPopupMenu() -> Any?
    {
        return _event
    }
    
    func view(_ view:UIView, click action:String, argument aArgument:[AnyHashable:Any]?)
    {
        if action == CallbackAction.Expand
        {
            photoViewExpand()
        }
        else if action == CallbackAction.Collapse
        {
            _photoView.collapse()
        }
    }
    
    func scrollViewDidScroll(_ scrollView: UIScrollView)
    {
        if scrollView.tag != MainScrollViewTag
        {
            return
        }
        
        let yOffset:CGFloat = scrollView.contentOffset.y
        if yOffset > 0
        {
            //头部悬停以显示SegmentedView
            if yOffset <= NavigationBarHoverY
            {
                //当快接近目标位置时，状态栏逐渐显示
                let AlphaGrid:CGFloat = 40
                let distance:CGFloat = NavigationBarHoverY - yOffset
                let progress:CGFloat = min(max((AlphaGrid - distance) / AlphaGrid, 0), 1)
                _navigationBar.alpha = distance < AlphaGrid ? progress : 0
            }
            else
            {
                //当快速上滑时，触发此事件的物理间隔将更大，就会出现headerView离临界位置有一定距离，因此需要手动强制复位
                if _navigationBar.alpha != 1
                {
                    _navigationBar.alpha = 1
                }
            }
        }
    }
    
    func imagePickerController(_ picker: SWImagePickerController, didFinishPickingMediaWithPhotos photos: [SWALPhoto])
    {
        //添加全局记录
        let event:SWKidEvent? = _event ?? SWKidEvent(eventID:eventID)
        let localIdentifiers:[String] = photos.flatMap({$0.localIdentifier}).filter({$0 != ""})
        let assets:[SWAssetRecord] = SWAssetsManager.sharedManager().addAssets(localIDs: localIdentifiers, event: event)
        let favorites:[SWAssetRecord] = assets.filter({$0.valid && $0.isFavorite})
        var favoritesPhotosCount:Int = 0
        var normalPhotosCount:Int = 0
        for photo in photos.reversed()
        {
            if favorites.contains(where: {$0.localID == photo.localIdentifier})
            {
                photo.selected = true
                _favoritePhotos.insertSafely(photo, atIndex: 0)
                favoritesPhotosCount += 1
            }
            else
            {
                _photos.insertSafely(photo, atIndex: 1)
                normalPhotosCount += 1
            }
        }
        
        if favoritesPhotosCount > 0
        {
            _photoView.hCollectionView?.reloadData()
        }
        
        if normalPhotosCount > 0
        {
            _photoView.vCollectionView?.reloadData()
        }
        
        picker.close()
    }
    
    func imagePickerControllerDidCancel(_ picker: SWImagePickerController)
    {
        picker.close()
    }
    
    func eventPhotosViewWillPresent(view:SWEventPhotosView)
    {
        _container.isScrollEnabled = false
        UIView.animate(withDuration: 0.3, animations: {
            self._expandBtn.alpha = 0
        })
    }
    
    func eventPhotosViewWillDismiss(view:SWEventPhotosView)
    {
        _container.isScrollEnabled = true
        UIView.animate(withDuration: 0.3, animations: {
            self._expandBtn.alpha = 1
        })
    }
    
    func eventPhotosViewShare(view:SWEventPhotosView)
    {
        var photos:[SWALPhoto] = []
        photos += _favoritePhotos
        photos += _photos
        
        photos = photos.flatMap({$0.clone()})
        for (i,photo) in photos.enumerated()
        {
            photo.index = i
            photo.selected = false
        }
        
        //
        //TODO 泄露
        let photosViewCtroller = SWALPhotosCollectionViewController(photos: photos)
        photosViewCtroller.delegate = self
        photosViewCtroller.allowsMultipleSelection = true
        photosViewCtroller.maxCount = 0
        
        let navigation = SWBaseNavigationController(rootViewController: photosViewCtroller)
        
        /**
        //weak var navigationController:UINavigationController? = navigation
        photosViewCtroller.chooseCallback = {[weak navigation] selectedPhotos in
            
            let collageViewController = SWLargeCollageViewController()
            collageViewController.photos = selectedPhotos
            navigation?.pushViewController(collageViewController, animated: true)
        }
        photosViewCtroller.cancelCallback = {[weak self] in
            //photosViewCtroller.close()
        }**/
        
        present(navigation, animated: true, completion:nil)
    }
    
    func photosCollectionViewController(_ viewController: SWALPhotosCollectionViewController, didFinishChooseWithPhotos photos: [SWALPhoto])
    {
        let collageViewController = SWLargeCollageViewController()
        collageViewController.photos = photos
        viewController.navigationController?.pushViewController(collageViewController, animated: true)
        
    }
    
    func photosCollectionViewControllerDidCancel(_ viewController: SWALPhotosCollectionViewController)
    {
        viewController.close()
    }
    
    @objc private func deleteAssetNotification(_ notification:Notification)
    {
        print("deleteAssetNotification")
        if let localID = notification.userInfo?[SWKey.localID] as? String
        {
            removePhoto(localID: localID, photos: &_photos, collectionView:_photoView.vCollectionView)
            removePhoto(localID: localID, photos: &_favoritePhotos, collectionView:_photoView.hCollectionView)
        }
    }
    
    @objc private func assetChangedNotification(_ notification:Notification)
    {
        trace("assetChangedNotification")
        if let oldLocalID = notification.userInfo?[SWKey.oldLocalID] as? String,
            let newLocalID = notification.userInfo?[SWKey.newLocalID] as? String, oldLocalID != "" && newLocalID != ""
        {
            replacePhoto(oldLocalID: oldLocalID, newLocalID: newLocalID, photos: &_photos, collectionView: _photoView.vCollectionView)
            replacePhoto(oldLocalID: oldLocalID, newLocalID: newLocalID, photos: &_favoritePhotos, collectionView: _photoView.hCollectionView)
        }
    }
    
    //返回按钮
    @objc private func backBtnTapped()
    {
        navigationController?.popViewController(animated: true)
    }
    
    @objc private func expandBtnTapped()
    {
        photoViewExpand()
    }
    
    
    @objc private func collectBtnTapped()
    {
        guard let eventID = _event?.eventID, eventID != "" else{
            return
        }
        
        _collectBtn.isSelected ? dislikeKidEvent(eventID) : likeKidEvent(eventID)
        _collectBtn.isEnabled = false
    }
    
}

